﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using LogLib;
using IPCPhotoEditor.ChildForms;
using System.Diagnostics;
using KAImage;
using KAImage.Config;
using KAImage.AlgorAction;

namespace IPCPhotoEditor
{
    public partial class FormWorkBench : Form
    {
        private string _srcFileName = "";

        private Pen blackPen = new Pen(Color.Gray, 1);

        private ImageBrowser browser = null;

        private List<ToolStripMenuItem> listStripMenuItems = new List<ToolStripMenuItem>();

        private FormHistograms histograms = null;
        public FormWorkBench()
        {
            InitializeComponent();
            browser = new ImageBrowser();
            GetAllFunctionMenuItems();
            histograms = new FormHistograms();
        }

        private void GetAllFunctionMenuItems()
        {
            foreach (ToolStripMenuItem c in menuStrip1.Items)
            {
                if (c.DropDownItems.Count > 0)
                {
                    foreach (ToolStripMenuItem dc in c.DropDownItems)
                    {
                        listStripMenuItems.Add(dc);
                    }
                }               
            }         
        }

        private void SetMenuItemsEnabled(bool enabled)
        {
            for (int i = 0; i < listStripMenuItems.Count; i++ )
            {
                listStripMenuItems[i].Enabled = enabled;
            }
        }

        private void BrowseFileInfo_Reported(object sender, BrowseFileInfoReportedEventArgs e)
        {
            toolStripStatusLabel2.Text = e.FileInfo;
            _srcFileName = e.FileName;
        }

        private void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Log.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {         
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            histograms.TopLevel = false;
            panel2.Controls.Clear();
            panel2.Controls.Add(histograms);
            histograms.Show();
            browser.BrowsedImageUpdated += histograms.BrowsedImage_Updated;
            browser.BrowseFileInfoReported += BrowseFileInfo_Reported;
            panel1.Controls.Add(browser);
            SetDefaultDirectory();
        }

        private void SetDefaultDirectory()
        {
            DateTime dt = DateTime.Now;
            browser.SetDirectory(KAConfigs.Browse.DefaultBrowseFolder);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            browser.BrowsedImageUpdated -= histograms.BrowsedImage_Updated;
            browser.BrowseFileInfoReported -= BrowseFileInfo_Reported;
            panel1.Controls.Clear();
            histograms.Close();
            panel2.Controls.Clear();
        }

        private void ShowSaveFileDialog()
        {
            SaveFileDialog sfd = new SaveFileDialog();           
            //设置文件类型 
            sfd.Filter = "JPG(*.jpg)|*.jpg|PNG(*.png)|*.png|BMP(*.bmp)|*.bmp";
            sfd.FilterIndex = 1;
            sfd.RestoreDirectory = true;     
            //sfd.DefaultExt = ".png";
            sfd.FileName = _srcFileName + DateTime.Now.ToString("_yyMMddhhmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string saveFilePath = sfd.FileName;
                browser.SaveAsNewImage(saveFilePath);
            }       
        }

        private void 浏览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog form = new FolderBrowserDialog();
            form.SelectedPath = "D:";
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                browser.SetDirectory(form.SelectedPath);
            }
            else
            {
                SetMenuItemsEnabled(browser.HasImage);
            }
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog form = new OpenFileDialog();
            form.InitialDirectory = "D:";
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = form.FileName;
                browser.SetSingleImage(fileName);
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!browser.HasImage)
            {
                return;
            }
            ShowSaveFileDialog();
        }

        private void 色阶ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!browser.HasImage)
            {
                return;
            }
            SetMenuItemsEnabled(false);
            browser.SetPageButtonEnabled(false);

            FormLevel form = new FormLevel(browser.WorkImage);
            form.WorkImageUpdated += browser.WorkImage_Updated;
            form.FormClosing += OnChildFormClosing;      
            form.Show();
        }

        private void 曲线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!browser.HasImage)
            {
                return;
            }
            SetMenuItemsEnabled(false);
            browser.SetPageButtonEnabled(false);
            histograms.EnableUpdated = false;

            FormCurves form = new FormCurves(browser.WorkImage);
            form.FormClosing += OnChildFormClosing;
            form.WorkImageUpdated += browser.WorkImage_Updated;
            form.Show();
        }

        private void OnChildFormClosing(object sender, FormClosingEventArgs e)
        {
            Form f = sender as Form;
            DialogResult res = f.DialogResult;
            SetMenuItemsEnabled(true);
            browser.SetPageButtonEnabled(true);
            histograms.EnableUpdated = true;
            if (res == System.Windows.Forms.DialogResult.OK)
            {
                histograms.ShowHistograms(browser.WorkImage);
            }
            else
            {
                if (browser.HasImage)
                {
                    browser.ResetImage();
                }
            }
        }

        private void ShowMergingForm(Bitmap bmp)
        {
            SetMenuItemsEnabled(false);
            browser.SetPageButtonEnabled(false);

            FormMerging form = new FormMerging(bmp);
            form.FormClosing += OnChildFormClosing;
            form.WorkImageUpdated += browser.WorkImage_Updated;
            form.Show();
        }

        private void ShowEffectingForm(Bitmap bmp)
        {
            SetMenuItemsEnabled(false);
            browser.SetPageButtonEnabled(false);
            FormImageEffects form = new FormImageEffects(bmp);
            form.FormClosing += OnChildFormClosing;
            form.WorkImageUpdated += browser.WorkImage_Updated;
            form.Show();
        }

        private void 撤销所有修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (browser.HasImage)
            {
                browser.ResetImage();
            }
        }

        private void 高斯模糊ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (browser.HasImage)
            {
                ShowEffectingForm(browser.WorkImage);
            }
        }

        private void 全通道ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap bmp = browser.WorkImage;
            ImageEnhancement.HistogramEqualize(bmp);
            browser.UpdateWorkImage();
        }

        private void 单通道ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap bmp = browser.WorkImage;
            ImageEnhancement.HistogramEqualizeS(bmp);
            browser.UpdateWorkImage();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.L))
            {
                色阶ToolStripMenuItem_Click(this, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.M))
            {
                曲线ToolStripMenuItem_Click(this, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.H))
            {
                kW合成ToolStripMenuItem_Click(this, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.U))
            {
                色相饱和度ToolStripMenuItem_Click(this, null);
                return true;
            }
            if (keyData == (Keys.Control | Keys.G))
            {
                高斯模糊ToolStripMenuItem_Click(this, null);
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void 色相饱和度ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetMenuItemsEnabled(false);
            browser.SetPageButtonEnabled(false);
            FormHueSat form = new FormHueSat(browser.WorkImage);
            form.FormClosing += OnChildFormClosing;
            form.WorkImageUpdated += browser.WorkImage_Updated;
            form.Show();
        }

        /// <summary>
        /// 响应组合快捷键菜单命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormWorkBench_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void kW合成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowMergingForm(browser.WorkImage);
        }

        private void 设置默认浏览路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormFolderSetting form = new FormFolderSetting();
            form.ShowDialog();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAbout form = new FormAbout();
            form.ShowDialog();
        }

        private void 查看并设置应用方案ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormApplyConfig form = new FormApplyConfig();
            form.ShowDialog();
        }

        private void 对当前图像应用所有设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CustomActions a = new CustomActions(browser.WorkImage);
            a.WorkImageUpdated += browser.WorkImage_Updated;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            a.Execute();
            sw.Stop();
            MessageBox.Show("耗时:" + sw.ElapsedMilliseconds.ToString());
        }

        private void 导出方案配置文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormExportConfigFile form = new FormExportConfigFile();
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (ConfigFiles.ExportSettings(form.SelectedPath))
                {
                    MessageBox.Show("方案导出成功!");
                }
                else
                {
                    MessageBox.Show(ConfigFiles.ErrorMessage);
                }
            }
        }
    }
}

//Graphics g = panel1.CreateGraphics();
////画一个椭圆
//g.DrawImage(image, new Rectangle(0, 0, 200, 240), new Rectangle(400,1000, 200, 240), GraphicsUnit.Pixel);
//g.Dispose();
